<?php

namespace app\modules\backend\controllers;

use app\models\Base;
use app\models\Good;
use app\models\Specs;
use app\models\GoodPrice;
use app\tools\Img;
use app\tools\Re;
use Yii;
use yii\helpers\Json;

class GoodController extends BaseController
{
    public $audit_status_arr = ['待审核', '审核通过', '审核失败'];

    public function actionSpecsList(){
        $page = Yii::$app->request->post('page', 0);
        $type = Yii::$app->request->post('type', 0);
        $name = Yii::$app->request->post('name', 0);
        $parent_id = Yii::$app->request->post('parent_id', 0);
        $specs_query = Specs::find()->where(['status' => [0,1]]);
        if ($type) {
          $specs_query->andWhere('parent_id <> 0');
        } else {
          $specs_query->andWhere(['parent_id' => 0]);
        }
        if ($name) {
            $specs_query->andWhere(['like', 'name', $name]);
        }
        if ($parent_id) {
          $specs_query->andWhere(['parent_id' => $parent_id]);
        }
        $specs_list = $specs_query->orderBy("created_at desc")->limit(Specs::PAGE_SIZE)->offset(Specs::PAGE_SIZE*$page)->all();
        $specs_data = [];
        if ($specs_list) {
            foreach ($specs_list as $v) {
                $specs_data[] = [
                    'id' => $v->id,
                    'name' => $v->name,
                    'parent_id' => $v->parent_id,
                    'parent_name' => $v->parent_id ? $v->parent->name : '',
                    'status' => $v->status,
                    'created_time' => date("Y-m-d H:i", $v->created_at),
                ];
            }
        }
        return Re::data([
            'data' => $specs_data,
            'totalPage' => $specs_query->count(),
            'currentPage' => $page,
            'perPage' => Specs::PAGE_SIZE
        ]);
    }

    public function actionEditSpecs(){
        $id = Yii::$app->request->post('id', 0);
        $post = Yii::$app->request->post();
        $specs_old = Specs::find()->where(['name' => $post['name']])->andWhere("id <> '$id'")->one();
        if ($specs_old) {
            return Re::data(null, '信息已存在', Re::ERROR);
        }
        $post['code'] = rand(1,999999);
        return $this->edit(Specs::class, $id, $post);
    }

    public function actionChangeSpecsStatus(){
        $id = Yii::$app->request->post('id', 0);
        $status = Yii::$app->request->post('status', 0);
        $specs = Specs::findOne($id);
        if (empty($specs)) {
            return Re::data(null, '信息读取失败', Re::ERROR);
        }
        $specs->status = $specs->status ? 0 : 1;
        if (!$specs->save()) {
            return Re::data(null, '操作失败', Re::ERROR);
        }
        return Re::data();
    }

    public function actionSpecsListForSelect(){
        $type = Yii::$app->request->post('type', 1);
        if ($type == 1) {
          $specs_list = Specs::find()->where(['parent_id' => 0, 'status' => 1])->all();
          return Re::data(['data' => $specs_list]);
        } else {
          $specs_ids = Yii::$app->request->post('specs_ids', '');
          $specs_arr = $specs_ids ? explode(',', $specs_ids) : [];
          $all_specs_data = [];
          $specs_one_list = Specs::find()->where(['parent_id' => 0])->orderBy("created_at desc")->all();
          if (!empty($specs_one_list)) {
              foreach ($specs_one_list as $v1) {
                  $specs_two_data = [];
                  $specs_two_list = Specs::find()->where(['parent_id' => $v1->id])->orderBy("created_at desc")->all();
                  if (!empty($specs_two_list)) {
                      foreach ($specs_two_list as $v2) {
                          $specs_two_data[] = [
                              'id' => $v2->id,
                              'title' => $v2->name,
                              'parent_id' => $v2->parent_id,
                              'checked' => in_array($v2->id, $specs_arr)
                          ];
                      }
                  }
                  $all_specs_data[] = [
                      'id' => $v1->id,
                      'title' => $v1->name,
                      'parent_id' => $v1->parent_id,
                      'children' => $specs_two_data
                  ];
              }
          }
          return Re::data(['data' => $all_specs_data]);
        }
    }

    public function actionGoodPriceList(){
        $specs_obj_str = Yii::$app->request->post('specs_obj_str', '');
        $specs_obj_arr = json_decode($specs_obj_str);
        //var_dump($specs_obj_arr);die;
        $res = array();
        foreach ($specs_obj_arr as $v) {
            $res = $this->array_cartesian_product($v);
        }
        //var_dump($res);die;
        $specs_list = Specs::find()->where(['status' => 1])->andWhere("parent_id <> 0")->all();
        $res_data = [];
        foreach ($res as $v) {
            $specs_info = $this->getSpecsInfo($v, $specs_list);
            $res_data[] = [
                'specs_code' => $specs_info['specs_code'],
                'specs_name' => $specs_info['specs_name'],
                'specs_price' => ''
            ];
        }
        return Re::data(['data' => $res_data]);
    }

    private function getSpecsInfo($code, $list) {
        $specs_code = 0;
        $specs_name = '';
        $code_arr = explode('_', $code);
        foreach ($code_arr as $v) {
            foreach ($list as $v1) {
                if ($v == $v1->id) {
                    $specs_code += $v1->code;
                    $specs_name .= $v1->name . '_';
                }
            }
        }
        $specs_name = rtrim($specs_name, "_");
        $data = [
          'specs_code' => $specs_code,
          'specs_name' => $specs_name,
        ];
        return $data;
    }

    private function array_cartesian_product($val) {
        static $res = array();
        if(empty($res)) {
            $res = $val;
        } else{
            // 临时数组保存结合的结果
            $list = array();
            foreach ($res as $k => $v) {
                foreach ($val as $key => $value) {
                   //var_dump($value->id);
                   $list[$k.'_'.$key] = $v.'_'.$value;
                }
            }
            $res = $list;
        }
        return $res;
    }

    public function actionGoodList(){
        $page = Yii::$app->request->post('page', 0);
        $name = Yii::$app->request->post('name', 0);
        $cate_id = Yii::$app->request->post('cate_id', 0);
        $type = Yii::$app->request->post('type', 0);
        $good_query = Good::find()->where(['status' => [0,1]]);
        if ($name) {
            $good_query->andWhere(['like', 'name', $name]);
        }
        if ($cate_id) {
            $good_query->andWhere(['cate_id' => $cate_id]);
        }
        if ($type) {
            $good_query->andWhere(['type' => $type]);
        } else {
            $good_query->andWhere(['type' => [1,2]]);
        }
        $good_list = $good_query->orderBy("sort desc, created_at desc")->limit(Good::PAGE_SIZE)->offset(Good::PAGE_SIZE*$page)->all();
        $good_data = [];
        if ($good_list) {
            foreach ($good_list as $v) {
                $good_data[] = [
                    'id' => $v->id,
                    'name' => $v->name,
                    'cover' => $v->cover,
                    'cate_name' => $v->cate->name,
                    'cate_id' => $v->cate_id,
                    'content' => $v->content,
                    'specs_ids' => $v->specs_ids,
                    'specs_obj_str' => $v->specs_obj_str,
                    'sort' => $v->sort,
                    'is_zl' => $v->is_zl,
                    'is_pay' => $v->is_pay,
                    'is_have_specs' => $v->is_have_specs,
                    'type' => $v->type,
                    'unit' => $v->unit,
                    'unit_type' => $v->unit_type,
                    'sale_count' => $v->sale_count,
                    'price' => $v->price,
                    'status' => $v->status,
                    'audit_status' => $v->audit_status,
                    'audit_status_name' => $this->audit_status_arr[$v->audit_status],
                    'created_time' => date("Y-m-d H:i", $v->created_at),
                ];
            }
        }
        return Re::data([
            'data' => $good_data,
            'totalPage' => $good_query->count(),
            'currentPage' => $page,
            'perPage' => Good::PAGE_SIZE
        ]);
    }

    public function actionEditGood(){
        $id = Yii::$app->request->post('id', 0);
        $post = Yii::$app->request->post();
        $post['price'] = $post['price'] ?: 0;
        if($id){
            $good = Good::findOne($id);
            if(!$good) {
                return Re::data(null, '商品信息读取失败', Re::ERROR);
            }
        } else{
            $good = new Good();
        }
        $good->load($post, '');
        if (!$good->save()) {
            return Re::data(null, $good->showErrors(), Re::ERROR);
        }
        if($post['specs_price_str']){
          GoodPrice::deleteAll(['good_id' => $good->id]);
          $specs_price_str = $post['specs_price_str'];
          $specs_price_arr = json_decode($specs_price_str);
          foreach ($specs_price_arr as $v) {
            $good_price = new GoodPrice();
            $good_price->good_id = $good->id;
            $good_price->specs_code = (string)$v->specs_code;
            $good_price->specs_name = $v->specs_name;
            $good_price->specs_price = $v->specs_price;
            $good_price->status = 1;
            $good_price->created_at = time();
            if (!$good_price->save()) {
              return Re::data(null, $good_price->showErrors(), Re::ERROR);
            }
          }
        }
        return Re::data();
    }

    public function actionGoodDetail(){
        $id = Yii::$app->request->post('id', 0);
        $good = Good::findOne($id);
        if (!$good) {
            return Re::data(null, '商品信息读取失败', Re::ERROR);
        }
        $good_price_list = GoodPrice::find()->where(['good_id' => $id])->all();
        $good_price_data = [];
        if ($good_price_list) {
          foreach ($good_price_list as $v) {
            $good_price_data[] = [
              'specs_code' => $v->specs_code,
              'specs_name' => $v->specs_name,
              'specs_price' => floatval($v->specs_price),
            ];
          }
        }
        $data = [
          'id' => $good->id,
          'name' => $good->name,
          'cover' => $good->cover,
          'cate_name' => $good->cate->name,
          'cate_id' => $good->cate_id,
          'content' => $good->content,
          'specs_ids' => $good->specs_ids,
          'specs_obj_str' => $good->specs_obj_str,
          'specs_price_str' => json_encode($good_price_data),
          'sort' => $good->sort,
          'type' => $good->type,
          'is_have_specs' => $good->is_have_specs,
          'is_zl' => $good->is_zl,
          'is_pay' => $good->is_pay,
          'unit' => $good->unit,
          'unit_type' => $good->unit_type,
          'sale_count' => $good->sale_count,
          'price' => $good->price,
          'status' => $good->status,
          'audit_status' => $good->audit_status,
          'created_time' => date("Y-m-d H:i", $good->created_at),
        ];
        return Re::data(['data' => $data]);
    }

    public function actionChangeGoodStatus(){
        $id = Yii::$app->request->post('id', 0);
        $status = Yii::$app->request->post('status', 0);
        $good = Good::findOne($id);
        if (empty($good)) {
            return Re::data(null, '商品读取失败', Re::ERROR);
        }
        $good->status = $status;
        if (!$good->save()) {
            return Re::data(null, '操作失败', Re::ERROR);
        }
        return Re::data();
    }

    public function actionAuditGood(){
        $id = Yii::$app->request->post('id', 0);
        $audit_status = Yii::$app->request->post('audit_status', 1);
        $audit_content = Yii::$app->request->post('audit_content', 0);
        $good = Good::findOne($id);
        if (empty($good)) {
            return Re::data(null, '商品读取失败', Re::ERROR);
        }
        $good->audit_status = $audit_status;
        $good->audit_content = $audit_content;
        if (!$good->save()) {
            return Re::data(null, '操作失败', Re::ERROR);
        }
        return Re::data();
    }

    public function actionGoodSpecsList(){
        $good_id = Yii::$app->request->post('good_id', 0);
        $type = Yii::$app->request->post('type', 1);
        $name = Yii::$app->request->post('name', 0);
        $good = Good::findOne($good_id);
        if (empty($good_id) || empty($good)) {
            return Re::data(null, '商品读取失败', Re::ERROR);
        }
        $good_specs_query = GoodSpecs::find()->where(['good_id' => $good_id, 'type' => $type, 'status' => [0,1]]);
        if ($name) {
            $good_specs_query->andWhere(['like', 'name', $name]);
        }
        $good_specs = $good_specs_query->orderBy("created_at desc")->all();
        $good_specs_data = [];
        if ($good_specs) {
            foreach ($good_specs as $v) {
                $good_specs_data[] = [
                    'id' => $v->id,
                    'good_id' => $v->good_id,
                    'good_name' => $v->good->name,
                    'name' => $v->name,
                    'status' => $v->status,
                    'created_time' => date("Y-m-d H:i", $v->created_at),
                ];
            }
        }
        return Re::data(['data' => $good_specs_data]);
    }

    public function actionEditGoodSpecs(){
        $id = Yii::$app->request->post('id', 0);
        $post = Yii::$app->request->post();
        return $this->edit(GoodSpecs::class, $id, $post);
    }

    public function actionChangeGoodSpecsStatus(){
        $id = Yii::$app->request->post('id', 0);
        $status = Yii::$app->request->post('status', 0);
        $good_specs = GoodSpecs::findOne($id);
        if (empty($good_specs)) {
            return Re::data(null, '信息读取失败', Re::ERROR);
        }
        $good_specs->status = $status;
        if (!$good_specs->save()) {
            return Re::data(null, '操作失败', Re::ERROR);
        }
        return Re::data();
    }

    public function actionListForSelect(){
        $good_list = Good::find()->where(['status' => 1])->select('id, name')->orderBy('sort desc')->all();
        return Re::data(['data' => $good_list]);
    }

    public function actionAqList(){
      $name = Yii::$app->request->post('name', 0);
      $aq_query = GoodAq::find()->where(['status' => [0,1]]);
      if ($name) {
          $aq_query->andWhere(['like', 'name', $name]);
      }
      $aq_list = $aq_query->orderBy("created_at desc")->all();
      $aq_data = [];
      if ($aq_list) {
          foreach ($aq_list as $v) {
              $aq_data[] = [
                  'id' => $v->id,
                  'name' => $v->name,
                  'answer' => $v->answer,
                  'status' => $v->status,
                  'created_time' => date("Y-m-d H:i", $v->created_at),
              ];
          }
      }
      return Re::data(['data' => $aq_data]);
    }

    public function actionEditAq(){
        $id = Yii::$app->request->post('id', 0);
        $post = Yii::$app->request->post();
        return $this->edit(GoodAq::class, $id, $post);
    }

    public function actionChangeAqStatus(){
        $id = Yii::$app->request->post('id', 0);
        $status = Yii::$app->request->post('status', 0);
        $good_aq = GoodAq::findOne($id);
        if (empty($good_aq)) {
            return Re::data(null, '商品问答库信息读取失败', Re::ERROR);
        }
        $good_aq->status = $status;
        if (!$good_aq->save()) {
            return Re::data(null, '操作失败', Re::ERROR);
        }
        return Re::data();
    }

    public function actionChangeStatusBatch(){
        $ids = Yii::$app->request->post('ids', '');
        $status = Yii::$app->request->post('status', 1);
        $id_arr = explode(",", $ids);
        if ($id_arr) {
          foreach ($id_arr as $v) {
            $good = Good::findOne($v);
            if (empty($good)) {
                return Re::data(null, '商品信息读取失败', Re::ERROR);
            }
            $good->status = $status;
            if (!$good->save()) {
                return Re::data(null, '操作失败', Re::ERROR);
            }
          }
        }
        return Re::data();
    }
}
